import React,{useEffect,useState,useRef, useMemo} from 'react'
import './Home.css'
import { SideBar,Popup,Button,Badge } from 'antd-mobile'
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:8888'
import { useThrottleFn } from 'ahooks'
import { GiftOutline } from 'antd-mobile-icons'

export default function Home() {
  let [list,setList]=useState([])
  const [visible1, setVisible1] = useState(false)
  const subnum=(id)=>{
    axios.put(`/subnum/${id}`).then(()=>{
      getList()
    })
  }
  const addnum=(id)=>{
    axios.put(`/addnum/${id}`).then(()=>{
      getList()
    })
  }
  let gouList=useMemo(()=>{
    return list.filter(item=>item.num>0)
  },[list])
  const items = [
    { key: '1', title: '烫烫水水', text: list.slice(0,2).map(item=>{
      return <div key={item._id} className='pro-item'>
        <div className='pro-item-left'>
              <img src={item.img} alt=""  style={{width:'100px',height:'100px'}}/>
         p     <div className='pro-item-left-text'>
                <h2>{item.name}</h2>
                <h2>${item.price}</h2>
              </div>
              <div>
                <button onClick={()=>{subnum(item._id)}} style={{display:item.num==0?'none':'block'}}>-</button>
                <span>{item.num}</span>
                <button onClick={()=>{addnum(item._id)}}>+</button>
              </div>
        </div>
      </div>
    }) },
    {
      key: '2', title: '11', text: list.slice(2.4).map(item=>{
        return <div key={item._id} className='pro-item'>
          <div className='pro-item-left'>
                <img src={item.img} alt=""  style={{width:'100px',height:'100px'}}/>
                <div className='pro-item-left-text'>
                  <h2>{item.name}</h2>
                  <h2>${item.price}</h2> 
                </div>
                <div>
                  <button onClick={()=>{subnum(item._id)}} style={{display:item.num==0?'none':'block'}}>-</button>
                  <span>{item.num}</span>
                  <button onClick={()=>{addnum(item._id)}}>+</button>
                </div>
          </div>
        </div>
      })
    }
  ]
  useEffect(()=>{
    getList()

    const mainElement = mainElementRef.current
    if (!mainElement) return
    mainElement.addEventListener('scroll', handleScroll)
    return () => {
      mainElement.removeEventListener('scroll', handleScroll)
    }
  },[])

  let getList=async()=>{
    let res=await axios.get("/list")
    setList(res.data.data)
  }
  const [activeKey, setActiveKey] = useState('1')
  const { handleScroll } = useThrottleFn(
    () => {
      let currentKey = items[0].key
      for (const item of items) {
        const element = document.getElementById(`anchor-${item.key}`)
        if (!element) continue
        const rect = element.getBoundingClientRect()
        if (rect.top <= 0) {
          currentKey = item.key
        } else {
          break
        }
      }
      setActiveKey(currentKey)
    },
    {
      leading: true,
      trailing: true,
      wait: 100,
    }
  )

  const mainElementRef = useRef(null)


  return (
    <div className='container'>

      <div className='side'>
        
        <SideBar
          activeKey={activeKey}
          onChange={key => {
            document.getElementById(`anchor-${key}`)?.scrollIntoView()
          }}
        >
          {items.map(item => (
            <SideBar.Item key={item.key} title={item.title} />
          ))}

        </SideBar>
      </div>

      <div className='main' ref={mainElementRef}>
        {items.map(item => (
          <div key={item.key}>
            <h2 id={`anchor-${item.key}`}>{item.title}</h2>
            {item.text}
          </div>
        ))}
      </div>


      <div>
            <Button
                onClick={() => {
                  setVisible1(true)
                }}
                style={{position:'fixed',left:'50px',bottom:'30px'}}
              >
              底部弹出
            </Button>
            <Popup
              visible={visible1}
              onMaskClick={() => {
                setVisible1(false)
              }}
              onClose={() => {
                setVisible1(false)
              }}
            >
               <div className='popuo-header'>
                    <div onClick={() => {
                        axios.put('/setnum').then(() => {
                            getList()
                            setVisible1(false)
                        })
                    }}>删除</div>
                </div>
                <div>
                  {
                    gouList.map(item=>{
                      return <div key={item._id}>
                        <img src={item.img} style={{width:'100px',height:'100px'}}></img>
                        <p>{item.name}</p>
                        <p>${item.price}</p>
                        <div>
                          <button onClick={()=>{subnum(item._id)}} style={{display:item.num==0?'none':'block'}}>-</button>
                          <span>{item.num}</span>
                          <button onClick={()=>{addnum(item._id)}}>+</button>
                        </div>
                      </div>
                    })
                  }
                </div>
                <div>
                  {
                    gouList.length==0?<GiftOutline>

                    </GiftOutline>:<Badge content={gouList.reduce((pre,item)=>{
                      return pre+item.num
                    },0)}></Badge>
                  }
                  {
                    gouList.length==0?<div>购物车为空</div>:<div>总价：${gouList.reduce((pre,item)=>{
                      return pre+item.num*item.price
                    },0)}</div>
                  }
                </div>
            </Popup>
        </div>
    </div>
    
  )
}
 